# -*- coding: utf-8 -*-
"""
@version: 1.0
@author: Pyma
@file: views
@time: 2019/10/16 22:16
"""

from django.shortcuts import render
from django.urls import reverse

from .models import Payinfo, PayinfOrder
from apps.xfzauth.decorators import xfz_login_required
from django.http import FileResponse, Http404
from django.conf import settings
import os
from utils import restful

app_name = "payinfo"

def index(request):
    context = {
        'payinfos' : Payinfo.objects.all()
    }
    return render(request, "payinfo/payinfo_index.html", context=context)


@xfz_login_required
def payinfo_order(request):
    payinfo_id = request.GET.get("payinfo_id")
    payinfo = Payinfo.objects.get(pk=payinfo_id)
    order = PayinfOrder.objects.create(payinfo=payinfo, buyer=request.user, status=1, amount=payinfo.price)
    context = {
        'goods': {
            'thumbnail': '',
            'price': payinfo.price,
            'title':payinfo.title
        },
        "order": order,
        # /course/notify_url/
        "notify_url": request.build_absolute_uri(reverse("payinfo:notify_view")),
        # "return_url": request.build_absolute_uri(reverse("payinfo:download")+"?orderid="+order.pk)
        "return_url": request.build_absolute_uri(reverse("payinfo:index"))

    }
    return render(request, 'course/course_order.html', context=context)

# @csrf_exempt
def notify_view(request):
    orderid = request.POST.get("orderid")
    PayinfOrder.objects.filter(pk=orderid).update(status=2)
    return restful.ok()

@xfz_login_required
def download(request):
    payinfo_id = request.GET.get('payinfo_id')
    order = PayinfOrder.objects.filter(payinfo_id=payinfo_id, buyer=request.user, status=2).first()
    if order:
        payinfo = order.payinfo
        path = payinfo.path
        fp = open(os.path.join(settings.MEDIA_ROOT, path), 'rb')
        # 生成两个文件头方可下载
        response = FileResponse(fp)
        response['Content-Type'] = 'image/jpeg'
        response['Content-Disposition'] = 'attachment;filename="%s"' % path.split("/")[-1]
        # 文件作为附件下载
        return response
    else:
        return Http404



